<script lang="ts" setup name="RejectionEdit">
import { CircleClose, CirclePlus, Delete, Plus } from '@element-plus/icons-vue'
import { FormInstance, FormRules, TableInstance } from 'element-plus'
import { DefaultRow, TableColumnCtx } from 'element-plus/es/components/table/src/table/defaults.mjs'
import { createSupplierAPI, getGoodsList, getSupplierAPI, getSupplierAreaAPI, getWaresCategoryListAPI } from '~/src/api/goods'
import { Inventory } from '~/src/api/interface/goods'
import { Information } from '~/src/api/interface/information'
import { Procure } from '~/src/api/interface/procure'
import {
  addRejectionAPI,
  checkRejectionAPI,
  editRejectionAPI,
  getRejectionDetailAPI,
  getRejectionListAPI,
  getStoreHouseAPI,
} from '~/src/api/procure'
import { replaceArrayItems } from '~/src/utils'
import { formatDate } from '~/src/utils/date-formatter'
import { returnType } from '~/src/utils/serviceDict'
import SupplierDialog from '../../information/supplier/SupplierDialog.vue'
import QuickDialog from '../components/QuickDialog.vue'
import SelectTable from '/@vab/components/SelectTable/index.vue'
import SelectTreeTable from '/@vab/components/SelectTreeData/index.vue'

const route = useRoute()
onMounted(async () => {
  await Promise.all([getSupplier(), getRejectionDetail(), getStoreHouse()])
  getSupplier()
  if (!formData.value.checkFlag && !formData.value.sourceId) {
    add()
  }
})
const formData = ref<Procure.RejectionDetail>({
  date: formatDate(0, 'start', 'yyyy-MM-dd'),
  supplierId: 0,
  supplierName: '',
  address: '',
  contacts: '',
  mobile: '',
  id: 0,
  remark: '',
  status: 1,
  stockindetailList: [],
  returnType: 1,
  checkFlag: false,
  orderType: -1,
})
const rules = reactive<FormRules>({
  mobile: [
    {
      validator: (rules: any, value: string, callback: Function) => {
        const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        if (reg.test(value) || !value) return callback()
        callback(new Error('请输入正确手机号码'))
      },
      trigger: ['blur'],
    },
  ],
  date: [{ required: true, message: '' }],
  supplierId: [{ required: true, message: '' }],
})

const supplierList = ref<Array<Inventory.SupplierList>>([])
const getSupplier = async () => {
  const { data } = await getSupplierAPI({ pageSize: 999, pageNum: 1 })
  supplierList.value = data.list
  if (!route.query.id) formData.value.supplierId = data.list[0].id
}

const getRejectionDetail = async () => {
  if (route.query.orderNo) {
    const res = await getRejectionDetailAPI({ id: route.query.orderNo })
    formData.value = res.data
  }
}
const storeHouse = ref<Procure.StoreHouse[]>()
const defaultHouserId = ref(0)
const getStoreHouse = async () => {
  const { data } = await getStoreHouseAPI({ pageSize: 999, pageNum: 1 })
  storeHouse.value = data.list
  storeHouse.value.forEach((v) => {
    if (v.isDefault) {
      defaultHouserId.value = v.id
    }
  })
}

const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map((im: any) => {
      return {
        sn: im.sn,
        goodsName: im.name,
        goodsId: im.id,
        products: im.productName,
        productsId: im.prodcutId,
        productName: im.productName,
        quantity: 1,
        barcode: im.barcode,
        price: im.purPrice,
        amount: im.purPrice,
        taxRate: 0,
        isGift: false,
        giftQuantity: 0,
        // houseId: defaultHouserId.value,
        convert: im.convert,
        unitName: im.unitName,
        unitBasis: im.convert,
      }
    })
    formData.value.stockindetailList = replaceArrayItems(list, formData.value.stockindetailList, 'goodsId')
    // formData.value.stockindetailList = list;
  }
}

const add = (index: number = formData.value.stockindetailList.length) => {
  formData.value.stockindetailList.splice(index, 0, {
    goodsName: '',
    goodsId: 0,
    products: '',
    productsId: 0,
    productName: '',
    quantity: 0,
    price: 0,
    amount: 0,
    taxRate: 0,
    isGift: false,
    giftQuantity: 0,
    houseId: 0,
  })
}
const remove = (row: Inventory.ResGoodsList, index: number) => {
  if (!row.productsId) return
  formData.value.stockindetailList.splice(index, 1)
}

interface SummaryMethodProps<T extends DefaultRow = Inventory.ResPurchaseList> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const props: string[] = ['quantity', 'amount', 'giftQuantity']
  const sums: string[] = []
  columns.forEach((column: any, index: any) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (!props.includes(column.property)) {
      sums[index] = ''
      return
    }

    let valuesToSum: number[] = []
    data.forEach((item: any) => {
      if (column.property === 'quantity' && item.isGift) {
        return // 如果isGift为true，则不统计quantity
      }
      if (column.property === 'amount' && item.isGift) {
        return // 如果isGift为true，则不统计amount
      }
      if (column.property === 'giftQuantity' && !item.isGift) {
        return // 如果isGift为false，则不统计giftQuantity
      }
      const value = Number(item[column.property])
      if (!Number.isNaN(value)) {
        valuesToSum.push(value)
      }
    })

    if (valuesToSum.length > 0) {
      sums[index] = `${valuesToSum.reduce((prev, curr) => prev + curr, 0)}`
    } else {
      sums[index] = ''
    }
  })
  return sums
}
const formRef = ref<FormInstance>()
const router = useRouter()
const onSubmit = (type: string) => {
  if (formData.value.stockindetailList.filter((item) => item.goodsName).length < 1) return ElMessage.error('请选择商品')
  formRef.value!.validate(async (valid) => {
    if (!valid) return
    try {
      formData.value.stockindetailList = formData.value.stockindetailList.filter((item) => item.goodsId && item.productsId)
      if (route.query.type === 'edit') {
        await editRejectionAPI(formData.value).then(() => {
          router.push({
            path: '/procure/rejection',
          })
        })
      } else {
        await addRejectionAPI(formData.value).then(() => {
          router.push({
            path: '/procure/rejection',
          })
        })
      }
    } catch (error) {
      if (!formData.value.sourceId) {
        add(formData.value.stockindetailList.length)
      }
    }
  })
}

// 确认收货并审核
const onSubmitGoods = async () => {
  // if (!formData.value.supplierId) return ElMessage.error('请选择供应商')
  // if (!formData.value.createTime) return ElMessage.error('请选择退货日期')
  if (formData.value.stockindetailList.filter((item) => item.goodsName).length < 1) return ElMessage.error('请选择商品')
  await formRef.value!.validate()
  try {
    formData.value.stockindetailList = formData.value.stockindetailList.filter((item) => item.goodsId && item.productsId)
    await checkRejectionAPI(formData.value)
    ElMessage.success('审核成功')
    router.push({
      path: '/procure/rejection',
    })
  } catch (e) {
    if (!formData.value.sourceId) {
      add(formData.value.stockindetailList.length)
    }
  }
}

const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null)
const openSelectTreeTable = (title: string, searchVal?: string | number) => {
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: 'prodcutId',
    selTags: formData.value.stockindetailList
      .filter((age) => age.goodsId !== 0)
      .map((i) => {
        i.name = i.goodsName as string
        i.id = i.productsId as number
        return i
      }),
    columns: [
      { type: 'selection', width: 80 },
      { prop: 'barcode', label: '编码', align: 'left', width: 200 },
      { prop: 'sn', label: '代码', align: 'left', width: 200 },
      { prop: 'name', label: '商品名称', align: 'left', minWidth: 220 },
      { prop: 'productName', label: '规格', align: 'left', minWidth: 100 },
      { prop: 'unitName', label: '单位', align: 'left', minWidth: 160 },
      { prop: 'purPrice', label: '采购价格', minWidth: 120 },
      // { prop: "posPrice", label: "商品价格", minWidth: 120 }
    ],
    idName: 'goodsCategoryId',
    treeApi: getWaresCategoryListAPI,
    api: getGoodsList,
  }
  selectTreeTableRef.value?.acceptParams(params)
}
const onSupplierClick = () => {
  if (formData.value.stockindetailList.length > 1 || formData.value.stockindetailList.some((item, index) => !index && item.name))
    ElMessage.info('当前单据已有商品明细，不能更改供应商')
}
// 新增供应商start
const treeFilterData = ref<Information.SupplierAreaList[]>([])
const initData = reactive({
  id: 0,
  settleType: 1,
  businessType: 1,
  commissionRate: 0,
  monCheckCyclse: 30,
  checkOutCycle: 30,
})
const getTreeFilter = async () => {
  const { data } = await getSupplierAreaAPI({ pageNum: 1, pageSize: 9999 })
  treeFilterData.value = data.list
}
const dialogRef = ref<InstanceType<typeof SupplierDialog> | null>(null)
const addSupplier = async () => {
  await getTreeFilter()
  const params = {
    title: '新增',
    row: { ...initData, regionId: treeFilterData.value[0].id as number },
    isView: false,
    api: createSupplierAPI,
    areaList: treeFilterData.value,
    getTableList: getSupplier,
  }
  dialogRef.value?.acceptParams(params)
}

// 开启极速输入模式
const isQuick = ref(false)
const isQuickData = ref<number[]>([0, 1, 2])
const quickDialogRef = ref<InstanceType<typeof QuickDialog>>()
const inputList = [
  { label: '商品编码', value: 0 },
  { label: '数量', value: 1 },
  { label: '退货单价', value: 2 },
]
const quickSwitch = () => {
  if (isQuick.value) {
    isQuick.value = false
    isQuickData.value = [0, 1, 2]
    return
  }
  openQuickDialog()
}
const openQuickDialog = () => {
  quickDialogRef.value?.putParams({
    title: '',
    list: inputList,
    data: {
      list: isQuickData.value,
    },
  })
}
// 开启极速模式
const onQuick = (e: number[]) => {
  if (e.length > 2) return (isQuick.value = false)
  isQuick.value = true
  isQuickData.value = e
}

// 保存所有输入框 ref 的二维数组
const inputRefs = ref<(any | null)[][]>([])
const setInputRef = (rowIndex1: number, colIndex: number, el: any) => {
  if (!inputRefs.value[rowIndex1]) {
    inputRefs.value[rowIndex1] = []
  }
  inputRefs.value[rowIndex1][colIndex] = el
}
const handleEnter = (rowIndex1: number, colIndex: number) => {
  const value = inputRefs.value[rowIndex1][colIndex]
  if (!value) return // 没填，不跳
  // 是否开启极速输入模式
  if (!isQuick.value) {
    if (!colIndex) {
      // 1.barcode
      // 可搜索数据然后在跳转,barcode
      searchBarcode(rowIndex1, colIndex + 1)
      return
    }
    const isLastCol = colIndex === 2
    if (isLastCol) {
      // 3.换行
      const nextRow = rowIndex1 + 1
      if (inputRefs.value[nextRow] && inputRefs.value[nextRow][0]) {
        nextTick(() => {
          inputRefs.value[nextRow][0].focus()
          changeAmunt(rowIndex1)
        })
      }
    } else {
      // 2.正常数量行
      const nextCol = colIndex + 1
      if (inputRefs.value[rowIndex1][nextCol]) {
        nextTick(() => {
          inputRefs.value[rowIndex1][nextCol].focus()
          changeAmunt(rowIndex1)
        })
      }
    }
  } else {
    // 极速输入模式
    if (isQuickData.value.length === 1) {
      switch (isQuickData.value[0]) {
        case 0:
          searchBarcode(rowIndex1, colIndex + 1)
          break
        case 1:
        case 2:
          nextTick(() => {
            const nextRow = rowIndex1 + 1
            inputRefs.value[nextRow][isQuickData.value[0]].focus()
          })
          break
      }
    } else {
      const i1 = isQuickData.value[0]
      const i2 = isQuickData.value[1]
      if (!i1 && i2 === 1) {
        // 值为barcode 和 quantity
        if (!colIndex) {
          // 可搜索数据然后在跳转,barcode
          searchBarcode(rowIndex1, colIndex + 1)
          return
        } else {
          const isLastCol = colIndex === 1
          if (isLastCol) {
            const nextRow = rowIndex1 + 1
            if (inputRefs.value[nextRow] && inputRefs.value[nextRow][0]) {
              nextTick(() => {
                inputRefs.value[nextRow][0].focus()
                changeAmunt(rowIndex1)
              })
            }
          }
        }
      } else if (!i1 && i2 === 2) {
        // 值为0 和 2
        if (!colIndex) {
          // 可搜索数据然后在跳转,barcode
          searchBarcode(rowIndex1, colIndex + 2)
          return
        } else {
          const isLastCol = colIndex === 2
          if (isLastCol) {
            const nextRow = rowIndex1 + 1
            if (inputRefs.value[nextRow] && inputRefs.value[nextRow][0]) {
              nextTick(() => {
                inputRefs.value[nextRow][0].focus()
                changeAmunt(rowIndex1)
              })
            }
          }
        }
      } else {
        // 值为 1 和 2
        nextTick(() => {
          if (colIndex === 1) {
            const nextCol = colIndex + 1
            inputRefs.value[rowIndex1][nextCol].focus()
          } else {
            const nextRow = rowIndex1 + 1
            if (inputRefs.value[nextRow] && inputRefs.value[nextRow][0]) {
              nextTick(() => {
                inputRefs.value[nextRow][1].focus()
                changeAmunt(rowIndex1)
              })
            }
          }
          changeAmunt(rowIndex1)
        })
      }
    }
  }
}

// 商品实现键盘上下移动选中效果start
const goodsTableRef = ref<TableInstance>()
const goodsRowsCurrent = ref(0) // 拿到数据选中当前第一行,当他的索引是多少是goodslist就拿哪一个
const setCurrent = () => {
  goodsTableRef.value?.setCurrentRow(goodsList.value[goodsRowsCurrent.value])
  if (popoverVis.value && goodsList.value.length > 0) {
    nextTick(() => {
      inputRefs.value[rowIndex.value][0].blur()
      keyboardWrapperRef.value?.focus()
    })
  }
}
// 键盘控制上下选择
const handleKeydown = (e: KeyboardEvent): void => {
  const list = goodsList.value
  if (!list.length) return
  if (e.key === 'ArrowDown') {
    e.preventDefault()
    goodsRowsCurrent.value = (goodsRowsCurrent.value + 1) % list.length // 最后一行回到第一行
    goodsTableRef.value!.setCurrentRow(list[goodsRowsCurrent.value])
    nextTick(() => {
      goodsTableRef.value!.setScrollTop(getRowRelativeTop(goodsRowsCurrent.value).top)
    })
  }
  if (e.key === 'ArrowUp') {
    e.preventDefault()
    goodsRowsCurrent.value = (goodsRowsCurrent.value - 1 + list.length) % list.length // 第一行回到最后一行
    goodsTableRef.value!.setCurrentRow(list[goodsRowsCurrent.value])
    nextTick(() => {
      goodsTableRef.value!.setScrollTop(getRowRelativeTop(goodsRowsCurrent.value).top)
    })
  }
  if (e.key === 'Enter') {
    e.preventDefault()
    const current = list[goodsRowsCurrent.value]
    if (current) popoverClick(current)
  }
}
// 获取指定索引行相对于表格容器的 top 坐标
const getRowRelativeTop = (rowIndex: number): { top: number } => {
  if (!goodsTableRef.value) return { top: 0 }
  // 获取表格容器（整个 el-table 的 DOM 元素)
  const tableEl = goodsTableRef.value.$el as HTMLElement
  if (!tableEl) return { top: 0 }
  // 获取表格 body 容器（行所在的滚动容器）
  const bodyWrapper = goodsTableRef.value.$refs.bodyWrapper as {
    querySelectorAll(ele: string): HTMLElement[]
  }
  if (!bodyWrapper) return { top: 0 }
  // 获取指定行的 DOM 元素
  const rows = bodyWrapper.querySelectorAll('.el-table__row')
  if (!rows[rowIndex]) return { top: 0 } // 索引越界
  // 计算行相对于视口的 top 坐标
  const rowRect = rows[rowIndex].getBoundingClientRect()
  // 计算表格容器相对于视口的 top 坐标
  const tableRect = tableEl.getBoundingClientRect()

  // 行相对于表格容器的 top = 行视口 top - 表格视口 top
  const relativeTop = rowRect.top - tableRect.top
  // rows[rowIndex].scrollIntoView({ behavior: 'smooth' })
  return { top: relativeTop }
}

const keyboardWrapperRef = ref<HTMLDivElement | null>(null)
// 商品实现键盘上下移动选中效果end

// 搜索编码数据
const goodsList = ref<Inventory.ResGoodsList[]>([]) // 当前搜索数据
const rowIndex = ref(0) // 搜索行数据
const popoverVis = ref(false) // 搜索到数据后用于展示表格
const barcodeValue = ref<string | undefined>('')
const isOne = ref(false)
const onBarcodeFocus = (index: number) => {
  // barcode 用于当barcode有数据时候重新输入判断要不要搜索失去焦点时候把数据重新赋值
  rowIndex.value = index
  onFocus(index, 0)
  if (formData.value.stockindetailList[index].barcode) {
    nextTick(() => {
      barcodeValue.value = formData.value.stockindetailList[index].barcode
    })
  }
}
const onBarcodeBlur = (index: number) => {
  if (!popoverVis.value) {
    if (barcodeValue.value) {
      nextTick(() => {
        formData.value.stockindetailList[index].barcode = barcodeValue.value
        barcodeValue.value = ''
      })
      return
    }
    if (!isOne.value) {
      nextTick(() => {
        formData.value.stockindetailList[index].barcode = ''
        isOne.value = false
      })
    }
  }
}
const onClosePop = (index: number) => {
  popoverVis.value = false
  if (barcodeValue.value) {
    formData.value.stockindetailList[index].barcode = barcodeValue.value
    return
  }
  formData.value.stockindetailList[index].barcode = ''
}

const searchBarcode = async (row: number, col: number) => {
  goodsList.value = []
  if (
    (formData.value.stockindetailList[row].goodsName && formData.value.stockindetailList[row].barcode === barcodeValue.value) ||
    formData.value.sourceId
  ) {
    // 不开启极速搜索
    if (!isQuick.value) {
      // 当前行有数据,直接不搜索
      inputRefs.value[row][1]?.focus()
      return
    } else {
      // 当前行有数据,直接不搜索
      if (isQuickData.value.length <= 1) {
        inputRefs.value[row + 1][0]?.focus()
      } else {
        inputRefs.value[row][isQuickData.value.find((item) => item) as number]?.focus()
      }
      return
    }
  }
  if (!formData.value.stockindetailList[row].barcode || formData.value.stockindetailList[row].barcode!.length < 2) {
    ElMessage.info('请输入两个字以上关键字')
    return
  }
  const res = await getGoodsList({
    pageNum: 1,
    pageSize: 20,
    name: formData.value.stockindetailList[row].barcode,
    supplierId: formData.value.supplierId,
    isDefault: 0,
    isRetail: 1,
  })
  if (res.data.list.length === 1) {
    rowIndex.value = row
    popoverClick(res.data.list[0])
    isOne.value = true
  } else {
    goodsList.value = res.data.list
    popoverVis.value = true
    rowIndex.value = row
    goodsRowsCurrent.value = 0
    setCurrent()
  }
}
const popoverClick = (e: Inventory.ResGoodsList) => {
  // 选中行
  const i = formData.value.stockindetailList.findIndex((item) => item.productsId === e.prodcutId)
  if (i !== -1) {
    popoverVis.value = false
    ElMessageBox.confirm('当前商品已经添加，是否跳到对应行', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      nextTick(() => {
        if (formData.value.stockindetailList[rowIndex.value].goodsId) {
          formData.value.stockindetailList.splice(rowIndex.value - 1, 1)
        }
        goodsList.value = []
        inputRefs.value[i][0].focus()
      })
    })
    return
  }
  formData.value.stockindetailList[rowIndex.value] = {
    goodsName: e.name,
    goodsId: e.id,
    products: e.productName,
    productsId: e.prodcutId,
    productName: e.productName,
    quantity: 1,
    barcode: e.barcode,
    price: e.purPrice,
    amount: e.purPrice,
    taxRate: 0,
    isGift: false,
    giftQuantity: 0,
    houseId: 0, //defaultHouserId.value
    convert: e.convert,
    unitName: e.unitName,
    unitBasis: e.convert,
    sn: e.sn,
    lastInvoicePrice: e.lastInvoicePrice,
    stockUnit: e.stockUnit,
    stockCount: e.stockCount,
    defaultUnit: e.defaultUnit,
    purPrice: e.purPrice,
  }
  nextTick(() => {
    setTimeout(() => {
      if (!isQuick.value) {
        // 不开启极速模式
        inputRefs.value[rowIndex.value][1]?.focus()
      } else {
        // 开启极速模式
        if (isQuickData.value.length === 1) {
          inputRefs.value[rowIndex.value + 1][0]?.focus()
        } else {
          const i1 = isQuickData.value[0]
          const i2 = isQuickData.value[1]
          if (!i1 && i2 === 1) {
            // 值为0 和 1
            inputRefs.value[rowIndex.value][1]?.focus()
          } else if (!i1 && i2 === 2) {
            // 值为0 和 2
            inputRefs.value[rowIndex.value][2]?.focus()
          }
        }
      }
      rowIndex.value = 0
    }, 50)
    // inputRefs.value[rowIndex.value][1].focus()
    // 重置数据
    goodsList.value = []
    popoverVis.value = false
    // rowIndex.value = 0
    if (!formData.value.stockindetailList.some((item) => !item.goodsName)) add()
  })
}

// 数据和采购价修改自动修改金额
const changeAmunt = (index: number) => {
  nextTick(() => {
    formData.value.stockindetailList[index].amount = Number(
      ((formData.value.stockindetailList[index].quantity as number) * (formData.value.stockindetailList[index].price as number)).toFixed(4)
    )
    formData.value.stockindetailList[index].basicQuantity = Number(
      ((formData.value.stockindetailList[index].quantity as number) * (formData.value.stockindetailList[index].convert as number)).toFixed(
        2
      )
    )
    formData.value.stockindetailList[index].basePrice = Number(
      (
        (formData.value.stockindetailList[index].amount as number) / (formData.value.stockindetailList[index].basicQuantity as number)
      ).toFixed(2)
    )
  })
}
const onFocus = (row: number, col: number) => {
  nextTick(() => {
    inputRefs.value[row][col].select()
  })
}

// 导入收货单
const warehouseSheetRef = ref<InstanceType<typeof SelectTable>>()
const importWarehouseSheet = (title: string) => {
  warehouseSheetRef.value!.acceptParams({
    title,
    isView: false,
    selTags: formData.value.sourceId ? formData.value.sourceId : 0,
    mate: 'id',
    selType: 'radio',
    apiParams: { timeType: 2, orderType: 1, isRelation: 1 },
    width: 800,
    columns: [
      { type: 'radio', width: 80 },
      { prop: 'orderNo', label: '单据编号', minWidth: 180, align: 'left' },
      {
        prop: 'supplierName',
        label: '供应商',
        minWidth: 120,
        align: 'left',
      },
      { prop: 'createTime', label: '日期', minWidth: 120, align: 'left' },
    ],
    api: getRejectionListAPI,
  })
}

const radioProcureSheet = async (e: { data: Procure.ProcureSheet }) => {
  if (e.data.id === formData.value.sourceId) return
  const res = await getRejectionDetailAPI({ id: e.data.id, isRelation: 1 })
  formData.value.sourceId = e.data.id
  formData.value.sourceNo = e.data.orderNo
  formData.value.supplierId = res.data.supplierId
  formData.value.stockindetailList = res.data.stockindetailList.map((item) => {
    return {
      ...item,
      quantity: item.waitReturnQuantity,
      giftQuantity: item.waitGiftReturnQuantity,
      amount: item.amount,
    }
  })
}
</script>

<template>
  <div class="auto-height-container auto-height-container main-box">
    <header-line
      :confirmIsSHow="route.query.type !== 'view'"
      :title="(route.query.type === 'edit' ? '编辑' : route.query.type === 'add' ? '新增' : '查看') + '退货单'"
      @on-submit="onSubmit('')"
    >
      <template #button>
        <el-button v-if="route.query.type !== 'view'" class="ml5" type="primary" @click="quickSwitch">
          {{ isQuick ? '关闭快速输入' : '开启极速输入模式' }}
        </el-button>
        <el-button v-if="route.query.type !== 'view'" class="ml5" type="primary" @click="importWarehouseSheet('选择收货单')">
          导入收货单
        </el-button>
        <el-button
          v-if="route.query.type !== 'view' && !formData.sourceId"
          class="ml5"
          type="primary"
          @click="openSelectTreeTable('选择商品')"
        >
          选择商品
        </el-button>
        <el-button v-if="route.query.type !== 'view'" type="primary" @click="onSubmitGoods">保存并审核</el-button>
      </template>
    </header-line>
    <el-form ref="formRef" label-suffix="：" label-width="120px" :model="formData" :rules="rules">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="供应商" prop="supplierId">
            <div class="flx-align-center width100">
              <el-select
                v-model="formData.supplierId"
                :disabled="
                  formData.stockindetailList.length > 1 ||
                  formData.stockindetailList.some((item, index) => !index && item.name) ||
                  !!formData.sourceId
                "
                filterable
                placeholder=""
                @click="onSupplierClick"
              >
                <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-button
                :disabled="formData.stockindetailList.length > 1 || formData.stockindetailList.some((item, index) => !index && item.name)"
                :icon="Plus"
                link
                size="small"
                type="primary"
                @click="addSupplier"
              >
                新增
              </el-button>
            </div>
          </el-form-item>
          <!-- <el-form-item label="供应商">
              <el-select v-model="formData.supplierId" placeholder="">
                <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item> -->
        </el-col>
        <el-col :span="5">
          <el-form-item label="退货原因">
            <el-select v-model="formData.returnType" placeholder="">
              <el-option v-for="item in returnType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="退货人">
            <el-input v-model="formData.contacts" class="width240" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="退货电话" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="退货日期" prop="date">
            <el-date-picker v-model="formData.date" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="退货地址">
            <el-input v-model="formData.address" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.sourceId" :span="5">
          <el-form-item label="收货单号">
            <el-input v-model="formData.sourceNo" disabled @click="importWarehouseSheet('导入收货单')" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="flex1">
      <el-table
        border
        :data="formData.stockindetailList"
        row-key="id"
        show-summary
        style="width: 100%; height: 100%"
        :summary-method="getSummaries"
      >
        <el-table-column align="center" label="序号" prop="index" width="60">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" prop="operation" width="100">
          <template #default="{ $index, row }">
            <el-button v-if="!formData.sourceId" link size="small" type="primary" @click="add($index + 1)">
              <el-icon :color="`var(--el-color-primary)`"><circle-plus /></el-icon>
            </el-button>
            <el-button :icon="Delete" link size="small" @click="remove(row, $index)" />
          </template>
        </el-table-column>
        <el-table-column label="商品条码" prop="barcode" width="180">
          <template #default="{ row, $index }">
            <el-popover placement="bottom-start" :visible="rowIndex === $index && popoverVis" :width="600">
              <div ref="keyboardWrapperRef" class="table-keyboard-wrapper" tabindex="0" @keydown.prevent="handleKeydown">
                <el-table
                  ref="goodsTableRef"
                  :data="goodsList"
                  highlight-current-row
                  row-key="prodcutId"
                  style="height: 250px"
                  @row-dblclick="popoverClick"
                >
                  <el-table-column label="条码" prop="barcode" width="200" />
                  <el-table-column label="代码" prop="sn" width="200" />
                  <el-table-column label="名称" prop="name" width="100" />
                  <el-table-column label="规格" prop="productName" width="100" />
                  <el-table-column label="单位" prop="unitName" width="100" />
                  <el-table-column label="采购价" prop="purPrice" width="100" />
                </el-table>
              </div>
              <div class="flx-justify-between">
                <div class="fsize12 pt10 pl5">提示：双击选中商品</div>
                <el-icon class="mt10" :size="18" @click="onClosePop($index)"><circle-close /></el-icon>
              </div>
              <template #reference>
                <el-input
                  :ref="(el) => setInputRef($index, 0, el)"
                  v-model="row.barcode"
                  :disabled="route.query.type === 'view'"
                  placeholder=""
                  style="border: none !important"
                  @blur="onBarcodeBlur($index)"
                  @focus="onBarcodeFocus($index)"
                  @keydown.enter.prevent="handleEnter($index, 0)"
                >
                  <!-- @keyup.enter="handleKeyup($event, $index, 1, row.isGift)" -->
                  <template #prefix></template>
                </el-input>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="商品代码" prop="sn" width="180" />
        <el-table-column label="名称" prop="goodsName" width="160" />
        <!-- <el-table-column label="仓库" prop="houseId" width="160">
          <template #default="{ row, $index }">
            <el-select v-model="row.houseId" placeholder="">
              <el-option v-for="item in storeHouse" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </template>
        </el-table-column> -->
        <el-table-column label="规格" prop="productName" width="160" />
        <el-table-column label="单位" prop="unitName" width="160" />
        <el-table-column label="退换数量" prop="quantity" width="160">
          <template #default="{ row, $index }">
            <!-- <el-input-number v-model="row.quantity" :controls="false" :min="1" @keyup.enter="handleKeyup($event, $index, 2, row.isGift)" /> -->
            <input-number-float
              :ref="(el) => setInputRef($index, 1, el)"
              v-model:modelValue="row.quantity"
              autofocus
              class="width100"
              @blur="changeAmunt($index)"
              @focus="onFocus($index, 1)"
              @keydown.enter.prevent="handleEnter($index, 1)"
            />
          </template>
        </el-table-column>
        <el-table-column label="退货单价" prop="price" width="160">
          <template #default="{ row, $index }">
            <input-number-float
              :ref="(el) => setInputRef($index, 2, el)"
              v-model:modelValue="row.price"
              class="width100"
              @blur="changeAmunt($index)"
              @focus="onFocus($index, 2)"
              @keydown.enter.prevent="handleEnter($index, 2)"
            />
          </template>
        </el-table-column>
        <el-table-column label="金额" prop="amount" width="160" />

        <el-table-column label="换算率" prop="convert" width="120">
          <template #default="{ row }">
            <input-number-float v-model:modelValue="row.convert" class="width100" disabled />
          </template>
        </el-table-column>
        <el-table-column label="基本数量" prop="basicQuantity" width="100">
          <template #default="{ row, $index }">
            <input-number-float v-model:modelValue="row.basicQuantity" class="width100" disabled />
          </template>
        </el-table-column>
        <el-table-column label="基本单价" prop="basePrice" width="130">
          <template #default="{ row, $index }">
            <input-number-float v-model:modelValue="row.basePrice" class="width100" disabled />
          </template>
        </el-table-column>
        <el-table-column label="最近进价" prop="lastInvoicePrice" width="160">
          <template #default="{ row, $index }">
            <input-number-float v-model:modelValue="row.lastInvoicePrice" class="width100" disabled />
          </template>
        </el-table-column>
        <el-table-column label="已收货数量" prop="totalDeliveryQuantity" width="160">
          <template #default="{ row, $index }">
            <input-number-float v-model:modelValue="row.totalDeliveryQuantity" class="width100" disabled />
          </template>
        </el-table-column>
        <el-table-column label="已退货数量" prop="totalReturnQuantity" width="160">
          <template #default="{ row, $index }">
            <input-number-float v-model:modelValue="row.totalReturnQuantity" class="width100" disabled />
          </template>
        </el-table-column>
        <el-table-column label="赠品数量" prop="giftQuantity" width="160">
          <template #default="{ row }">
            <input-number-float v-model:modelValue="row.giftQuantity" class="width100" />
          </template>
        </el-table-column>
        <el-table-column label="库存单位" prop="stockUint" width="160" />
        <el-table-column label="库存数量" prop="stockCount" width="160" />
        <el-table-column label="基本单位" prop="defaultUnit" width="160" />
        <el-table-column label="备注" prop="remark" width="180">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <select-tree-table ref="selectTreeTableRef" @selected-list="handleSelectedTreeList" />
    <supplier-dialog ref="dialogRef" />
    <quick-dialog ref="quickDialogRef" @on-confirm="onQuick" />
    <!-- 收货单 -->
    <select-table ref="warehouseSheetRef" @radio="radioProcureSheet" />
  </div>
</template>

<style lang="scss" scoped>
// 数据更新时没有生效
:deep(.el-table thead .el-table__cell) {
  padding: 5px 0;
  background: #f2f3f5;
}
:deep(.el-table tfoot .el-table__cell) {
  padding: 5px 0;
  background: #f2f3f5;
}
:deep(.el-table .el-table__cell) {
  padding: 0;
}
:deep(.el-form-item) {
  margin-bottom: 10px;
}
</style>
